package com.dongjiantong.app.controller.quarantine;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dongjiantong.biz.enums.ReportType;
import com.dongjiantong.biz.service.EarMarkLifeReadeService;
import com.dongjiantong.common.exceptions.HttpCode;
import com.dongjiantong.common.exceptions.OPServerException;
import com.dongjiantong.common.model.Response;
import com.dongjiantong.common.web.sso.LoginInfo;
import com.dongjiantong.common.web.util.UserUtil;
import com.dongjiantong.openplatform.annotations.OpenBean;
import com.dongjiantong.openplatform.annotations.OpenMethod;
import com.dongjiantong.quarantine.model.Harmless;
import com.dongjiantong.quarantine.serviceImpl.BreedReportsFileReadService;
import com.dongjiantong.quarantine.serviceImpl.HarmlessReadService;
import com.dongjiantong.quarantine.serviceImpl.HarmlessWriteService;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by mz on 23/11/17.
 *
 */
@Slf4j
@OpenBean
public class HarmlessController {

    @Reference(version = "1.0.0")
    private HarmlessReadService harmlessReadService;

    @Reference(version = "1.0.0")
    private HarmlessWriteService harmlessWriteService;

    @Reference(version = "1.0.0")
    private BreedReportsFileReadService breedReportsFileReadService;

    @Reference(version = "1.0.0")
    private EarMarkLifeReadeService earMarkLifeReadeService;

    /**
     * 查询单据详情根据id
     * @param id 单据主键
     * @return Response<Harmless>
     */
    @OpenMethod(
            key = "find.harmless.by.id",
            paramNames = {"id"},
            httpMethods = RequestMethod.GET
    )
    public Response<Harmless> findById(Long id){

        if(id == null){
            throw new OPServerException(HttpCode.BUTCHER_FARM_ID_IS_NOT_EXIST.getCode(),HttpCode.BUTCHER_FARM_ID_IS_NOT_EXIST.getMessage());
        }

        try{
            Harmless harmless = harmlessReadService.findById(id);
            Map<String , Object> map = Maps.newHashMap();
            map.put("field","harmless_photos");
            map.put("type1",ReportType.HARMLESS.value());
            map.put("type2",1);
            map.put("relevanceId",id);
            List<String> harmless_photos = breedReportsFileReadService.findListByType(map);
            map.put("field","harmless_videos");
            map.put("type2",2);
            List<String> harmless_videos = breedReportsFileReadService.findListByType(map);
            map.put("field","harmless_video_snapshoots");
            map.put("type2",1);
            List<String> harmless_video_snapshoots = breedReportsFileReadService.findListByType(map);
            map.clear();
            map.put("reportId",id);
            map.put("reportType",ReportType.HARMLESS.value());
            List<String> earTagNumbers = earMarkLifeReadeService.findListByBreedReportId(map);
            harmless.setHarmless_photos(harmless_photos);
            harmless.setHarmless_videos(harmless_videos);
            harmless.setHarmless_video_snapshoots(harmless_video_snapshoots);
            harmless.setEar_tag_numbers(earTagNumbers);
            return Response.ok(harmless);
        }catch (Exception e){
            return Response.fail(HttpCode.INTERNAL_SERVER_ERROR.getCode(),HttpCode.INTERNAL_SERVER_ERROR.getMessage());
        }
    }

    /**
     * 养殖场的分页查询
     * @param pageNum 页码
     * @param pageSize 条数
     * @param farmId 养殖场id
     * @param statuses 状态
     * @return Response<PageInfo<Harmless>>
     */
    @OpenMethod(
            key = "paging.harmless.for.farm",
            paramNames = {"pageNum","pageSize","farmId","statuses"},
            httpMethods = RequestMethod.GET
    )
    public Response<PageInfo<Harmless>> pagingForFarm(Integer pageNum ,
                                                      Integer pageSize ,
                                                      Long farmId ,
                                                      List<Integer> statuses){

        if(farmId == null){
            throw new OPServerException(HttpCode.FARM_ID_IS_NOT_EXIST.getCode(),HttpCode.FARM_ID_IS_NOT_EXIST.getMessage());
        }
        try{
            Map<String , Object> map = Maps.newHashMap();
            if(statuses != null && !statuses.isEmpty()) map.put("statuses",statuses);
            map.put("farmId",farmId);
            map.put("deleteFlag",1);
            map.put("reportType", ReportType.QUARANTINE_ORIGIN_AREA.value());
            PageInfo<Harmless> pageInfo = harmlessReadService.pagingForFarm(pageNum,pageSize,map);
            return Response.ok(pageInfo);
        }catch (Exception e){
            return Response.fail(HttpCode.INTERNAL_SERVER_ERROR.getCode(),HttpCode.INTERNAL_SERVER_ERROR.getMessage());
        }
    }

    /**
     * 屠宰场的分页查询
     * @param pageNum 页码
     * @param pageSize 条数
     * @param butcherFarmId 屠宰场ID
     * @param statuses 状态
     * @return Response<PageInfo<Harmless>>
     */
    @OpenMethod(
            key = "paging.harmless.for.butcher",
            paramNames = {"pageNum","pageSize","butcherFarmId","statuses"},
            httpMethods = RequestMethod.GET
    )
    public Response<PageInfo<Harmless>> pagingForButcher(Integer pageNum ,
                                                         Integer pageSize ,
                                                         Long butcherFarmId ,
                                                         List<Integer> statuses){

        if(butcherFarmId == null){
            throw new OPServerException(HttpCode.BUTCHER_FARM_ID_IS_NOT_EXIST.getCode(),HttpCode.BUTCHER_FARM_ID_IS_NOT_EXIST.getMessage());
        }
        try{
            Map<String , Object> map = Maps.newHashMap();
            if(statuses != null && !statuses.isEmpty()) map.put("statuses",statuses);
            map.put("butcherFarmId",butcherFarmId);
            map.put("deleteFlag",1);
            List<Integer> reportTypes = new ArrayList<>();
            reportTypes.add(ReportType.ANEMOMETER_INSPECTION.value());
            reportTypes.add(ReportType.SYNCHRONOUS_INSPECTION.value());
            map.put("reportTypes", reportTypes);
            PageInfo<Harmless> pageInfo = harmlessReadService.pagingForButcher(pageNum,pageSize,map);
            return Response.ok(pageInfo);
        }catch (Exception e){
            return Response.fail(HttpCode.INTERNAL_SERVER_ERROR.getCode(),HttpCode.INTERNAL_SERVER_ERROR.getMessage());
        }
    }

    /**
     * 政府端的分页查询
     * @param pageNum 页码
     * @param pageSize 条数
     * @param butcherFarmId 屠宰场id
     * @param farmId 养殖场ID
     * @param fromDate 从时间
     * @param toDate 到时间
     * @param statuses 状态
     * @return Response<PageInfo<Harmless>>
     */
    @OpenMethod(
            key = "paging.harmless.for.gov",
            paramNames = {"pageNum","pageSize","butcherFarmId","farmId","fromDate","toDate","statuses"},
            httpMethods = RequestMethod.GET
    )
    public Response<PageInfo<Harmless>> pagingForGov(Integer pageNum ,
                                                     Integer pageSize ,
                                                     Long butcherFarmId ,
                                                     Long farmId,
                                                     String fromDate,
                                                     String toDate,
                                                     List<Integer> statuses){

        Date start = Strings.isNullOrEmpty(fromDate) ? null : DateTime.parse(fromDate).toDate();
        Date end = Strings.isNullOrEmpty(toDate) ? null : DateTime.parse(toDate).toDate();
        try{
            Map<String , Object> map = Maps.newHashMap();
            LoginInfo loginInfo = UserUtil.getCurrentUser();
            List<Long> butcherFarmIds = new ArrayList<>();
            if(butcherFarmId != null) {
                butcherFarmIds.add(butcherFarmId);
            }else {
                butcherFarmIds = loginInfo.getButcherFactoryIds();
            }
            List<Long> farmIds = new ArrayList<>();
            if(farmId != null){
                farmIds.add(farmId);
            }else {
                farmIds = loginInfo.getBreedFactoryIds();
            }
            map.put("butcherFarmIds",butcherFarmIds);
            map.put("farmIds",farmIds);
            map.put("deleteFlag",1);
            if (statuses != null && !statuses.isEmpty()) map.put("statuses",statuses);
            if (start != null) map.put("start",start);
            if (end != null) map.put("end",end);
            PageInfo<Harmless> pageInfo = harmlessReadService.pagingForGov(pageNum,pageSize,map);
            return Response.ok(pageInfo);
        }catch (Exception e){
            return Response.fail(HttpCode.INTERNAL_SERVER_ERROR.getCode(),HttpCode.INTERNAL_SERVER_ERROR.getMessage());
        }
    }

    /**
     * 更新无害化
     * @param harmless 无害化对象
     * @param toStatus 到状态
     * @return Response<Map<String , Object>>
     */
    @OpenMethod(
            key = "update.harmless",
            paramNames = {"harmless","toStatus"},
            httpMethods = RequestMethod.POST
    )
    public Response<Map<String , Object>> update(@RequestBody(required = true) Harmless harmless ,
                                    @RequestParam(required = false) Integer toStatus){

        if(harmless == null){
            throw new OPServerException(HttpCode.PRIMARY_PARAM_IS_NULL.getCode(),HttpCode.PRIMARY_PARAM_IS_NULL.getMessage());
        }
        if(harmless.getId() == null){
            throw new OPServerException(HttpCode.PRIMARY_KEY_ID_IS_NOT_EXIST.getCode(),HttpCode.PRIMARY_KEY_ID_IS_NOT_EXIST.getMessage());
        }
        try{
            Date date = new Date();
            harmless.setUpdated_at(date);
            harmless.setDelete_flag(1);
            LoginInfo loginInfo = UserUtil.getCurrentUser();
            Integer currentStatus = harmlessReadService.findStatusById(harmless.getId());
            if(currentStatus != null && !currentStatus.equals(harmless.getStatus())){
                throw new OPServerException(HttpCode.DOCUMENT_REPEAT_SUBMIT.getCode(),HttpCode.DOCUMENT_REPEAT_SUBMIT.getMessage());
            }
            return Response.ok(harmlessWriteService.update(harmless,toStatus,loginInfo));
        }catch (Exception e){
            return Response.fail(HttpCode.DATA_UPDATE_FAIL.getCode(),HttpCode.DATA_UPDATE_FAIL.getMessage());
        }
    }
}
